package com.iphone.extra;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.iphone.extra.view.BatteryPercentView;
import com.iphone.extra.view.IWidgetFrameLayout;
import com.iphone.extra.view.OnWidgetEventListener;

import java.util.Locale;

public class WidgetBatteryLayout extends IWidgetFrameLayout {

    private int mBatPercent = 0;
    private BatteryPercentView mPercentView;
    private TextView mPercentText;

    public WidgetBatteryLayout(Context context) {
        this(context, null, 0);
    }

    public WidgetBatteryLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetBatteryLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mPercentView = (BatteryPercentView) findViewById(R.id.battery_percent_view);
        mPercentText = (TextView) findViewById(R.id.battery_percent_text);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        getContext().registerReceiver(mIntentReceiver, filter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(mIntentReceiver);
    }

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                final int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                if (mBatPercent != level) {
                    mBatPercent = level;
                    if (mPercentView != null) {
                        mPercentView.updateBatteryPercent(level, mPercentText.getTextColors());
                    }
                    if (mPercentText != null) {
                        mPercentText.setText(String.format(Locale.US, "%d%%", level));
                    }
                }
            }
        }
    };

    @Override
    public boolean onCellClicked(String describe) {
        return true;
    }

    @Override
    public String getLabel(Resources res) {
        return res.getString(R.string.widget_label_battery);
    }
}
